﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using BillHelper;
using System.Diagnostics;
using TaxAssistantBase;
using System.Text;

namespace DemoForBillOcr
{
    public partial class SaoMiaoImg : Form
    {
        private AutomationBillOcr billOcr = new AutomationBillOcr();
        private WsdLogger smlog = new WsdLogger("SaoMiaoLog");
        private WsdLogger imglog = new WsdLogger("imgNumlog");
        private IList<string> batchID = new List<string>();//存储batchid
        private static string currentTime = "";
        private bool prossFor = true;
        IList<string> list = new List<string>();
        public SaoMiaoImg()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        public static void WaitData(string currentValue)
        {
            WsdLogger errorlog = new WsdLogger("errorLog");
            try
            {
                NamedPipeClientStreamTool.Write(currentValue);
            }
            catch (Exception e)
            {
                WsdLogger.yxlog("error", "管道发送报错：" + e.Message);
            }
        }
        public SaoMiaoImg(string[] chuanRcurrentTime)
        {
            if (chuanRcurrentTime.Length > 0)
            {
                currentTime = chuanRcurrentTime[0];
            }
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        //程序开始
        private void Form2_Load(object sender, EventArgs e)
        {
            Hide();
            bool b = true;
            try
            {
                b = initForm();
                createTodayDir();//创建今天存入的文件夹
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "初始化报错：" + ex.Message);
                Application.DoEvents();
                Thread.Sleep(20 * 1000);
                return;
            }
            if (b)
            {
                //启动扫描仪展示启动
                string message = "0$$扫描仪已启动,请背面朝上横向放入票据!";
               WaitData(message);
                WsdLogger.yxlog("error", "发送" + message);
                textlistdoewn();
                //主程序，循环处理扫描和识别
                kaishiJC();
            }
        }
        private void textlistdoewn()
        {
            StringBuilder sb = new StringBuilder();
            List<BatchInfo> compList = SharedDataDownload.VendorscompanyAll;
            foreach (BatchInfo bi in compList)
            {
                sb.AppendFormat("{0}-{1}" + "\r\n", bi.companyName, bi.companyTaxnum);//这里几列，写几列
            }
            string texurl = AppDomain.CurrentDomain.BaseDirectory + "VendorsCompListData.txt";
            File.WriteAllText(texurl, sb.ToString());//写入文件
        }
        private void createTodayDir()
        {
            var dd = AppDomain.CurrentDomain.BaseDirectory;
            string activeDir = dd;
            string newPath = Path.Combine(activeDir, "HandleWenJ\\" + currentTime);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
        }
        //循环扫描和识别
        private void kaishiJC()
        {
            try
            {
                while (true)
                {
                    Application.DoEvents();
                    try
                    {
                        kaishiOpen();
                        //kaishiOpenTest();
                    }
                    catch (Exception ex)
                    {
                        WsdLogger.yxlog("error", "循环扫描：" + ex.Message);
                        Hide();
                    }
                    Thread.Sleep(2 * 1000);
                }
            }
            catch (Exception ex)
            {
                Hide();
                WsdLogger.yxlog("error", "循环扫描异常：" + ex.Message);
            }
        }
        //初始化
        public bool initForm()
        {
            string strUserID = "2B2ADEFE5CB6650E2D9A";
            int recode = -1;
            try
            {
                recode = billOcr.InitForm(strUserID);
                WsdLogger.yxlog("error", "初始化recode" + recode);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "开始初始化A错误" + ex.Message);
                return false;
            }
            if (0 != recode)
            {
                int nErroLength;
                char[] erroBuffer = new char[256];
                try
                {
                    billOcr.GetErroInformation(recode, erroBuffer, out nErroLength);
                    WsdLogger.yxlog("error", "初始化失败原因：" + recode);
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "开始初始化B错误" + ex.Message);
                    return false;
                }
                Thread.Sleep(5 * 1000);
                return initForm();
            }
            var url = AppDomain.CurrentDomain.BaseDirectory;
            string newPath = Path.Combine(url, "mod\\gongzidan.mod");
            if (newPath != null)
            {
                m_strUsMod.Text = newPath;
                string path = newPath;
                LoadingMB(path);
                btn_selectPath_Click();
            }
            return true;
        }
        //加载模板
        private void LoadingMB(string path)
        {
            AutomationBillOcr billOcr = new AutomationBillOcr();
            List<int> modID = new List<int>();
            int recode = -1;
            modID.Add(ModelEnum.CUSTOM);//加载在定义票种
            try
            {
                recode = billOcr.LoadTemplate(path.ToString());
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "加载模板A错误" + ex.Message);
                return;
            }
            if (0 != recode)
            {
                int nErroLength;
                char[] erroBuffer = new char[256];
                try
                {
                    billOcr.GetErroInformation(recode, erroBuffer, out nErroLength);
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "加载模板B错误" + ex.Message);
                    return;
                }
                string errInfo = new string(erroBuffer);
                m_strResult.Text = "识别错误：" + errInfo;
                return;
            }
            modID.Add(ModelEnum.JDCFP);
            modID.Add(ModelEnum.TRAIN);
            modID.Add(ModelEnum.ZZS_INVOICE);
            modID.Add(ModelEnum.FLY);
            int[] selectedMod = new int[modID.Count];
            int i = 0;
            for (i = 0; i < modID.Count; i++)
            {
                selectedMod[i] = modID[i];
            }
            int reCode = -1;
            try
            {
                reCode = billOcr.SetFormTypes(selectedMod, modID.Count);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "加载模板C错误" + ex.Message);
                return;
            }
            modID.Clear();
            if (0 != reCode)
            {
                m_strResult.Text = "加载模板失败,错误代码:" + reCode;
                return;
            }
        }
        int isyouPice = 0;
        //int temps = 0;
        //开始扫描纸张
        private void kaishiOpen()
        {
            AutomationBillOcr billOcr = new AutomationBillOcr();
            Application.DoEvents();
            string tpImgName = "";
            int index = 0;
            string message = "";
            string strIndex = "";
            bool isHavePaper = false;
            int recode = -1;
            billOcr = new AutomationBillOcr();
            try
            {
                isHavePaper = billOcr.IfHavePaper();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "判断是否有纸：" + ex.Message);
                Thread.Sleep(1000);
                return;
            }
            if (isHavePaper)
            {
                Thread.Sleep(1000);
                message = "0$$扫描中...!";
                WaitData(message);
                //新的批次开始
                string batchid = currentTime + DateTime.Now.ToString("HHmmss") + new Random().Next(10000).ToString().PadLeft(4, '0');
                smlog.Write("进入纸张扫描");
                index = 0;
                try
                {
                    while (isHavePaper)
                    {
                        strIndex = string.Format("{0:D4}", ++index);
                        tpImgName = m_strImgPath.Text + "\\img_" + batchid + "_" + strIndex + ".jpg";
                        try
                        {
                            recode = billOcr.AcquireNewImage(tpImgName);
                        }
                        catch (Exception ex)
                        {
                            WsdLogger.yxlog("error", "是否有纸报错：" + ex.Message);
                            Thread.Sleep(1000);
                            return;
                        }
                        isHavePaper = billOcr.IsHavePaper();
                        //1.1复制图片到指定批次文件夹（按批次id生成）下****
                        CopyImgDaoFile(tpImgName, batchid);
                    }
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "纸张扫描过程中报错：" + ex.Message);
                }
                message = "0$$请背面朝上横向放入票据!";
                WaitData(message);
                //1.2批次结束时，调用ocr img exe
                //添加batchid
                //list.Add(batchid);
                //打开处理票据进程
                startProcess(batchid);
            }
            //else
            //{
            //    //if (list.Count > 0)
            //    //{
            //    //    //打开处理票据进程
            //    //    //   startProcess();
            //    //}
            //    //else
            //    //{
            //        //isyouPice++;
            //        //if (isyouPice == 550)
            //        //{
            //        //    isyouPice = 0;
            //        //    this.Close();
            //        //}
            //    //}
            //}
        }

        private void startProcess(string batchid)
        {
            //获取进程数
            //Process[] pro = Process.GetProcessesByName("ShiBieProject");
            //if (pro.Length <= 10)
            //{
            //    //当进程大于制定数字时将badchid存起来
            //    try
            //    {
            //        var first = list.First();
            //        list.Remove(first);
                    startShiBie(batchid);//打开识别进程
            //    }
            //    catch (Exception ex)
            //    {
            //        WsdLogger.yxlog("error", "获取进程数报错：" + ex.Message);
            //    }
            //}
        }

        public void startShiBie(string batchid)
        {
            startShiBie1(batchid);
        }
        public void startShiBie1(object obj)
        {
            string batchid = obj as string;
            var p = new Process();
            p.StartInfo.FileName = Path.Combine(Application.StartupPath, "ShiBieProject.exe");
            p.StartInfo.Arguments = batchid + " " + currentTime;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.Verb = "runas";
            try
            {
                p.Start();
            }
            catch (Exception e)
            {
                WsdLogger.yxlog("error", "打开进程异常，错误原因：" + e.Message);
            }
        }
        private void CopyImgDaoFile(string imgaddress, string batchid)
        {
            if (File.Exists(imgaddress))
            {
                string newPath = GetNewPath(imgaddress, batchid);
                try
                {
                    File.Copy(imgaddress, newPath, true);
                }
                catch (Exception es)
                {
                    WsdLogger.yxlog("error", "复制图片错误+ " + es.Message + "出错图片地址:" + newPath);
                }
            }
        }
        private void TestCopyImgDaoFile(string imgaddress, string batchid)
        {
            if (File.Exists(imgaddress))
            {
                string newPath = TestGetNewPath(imgaddress, batchid);
                try
                {
                    File.Copy(imgaddress, newPath, true);
                    File.Delete(imgaddress);
                }
                catch (Exception es)
                {
                    WsdLogger.yxlog("error", "复制图片错误+ " + es.Message + "出错图片地址:" + newPath);
                }
            }
        }
        private IList<string> GetBatchInfoDicForDir()
        {
            var WaitTestImg = AppDomain.CurrentDomain.BaseDirectory + "WaitTestImg";
            var HandleWenJ = AppDomain.CurrentDomain.BaseDirectory + "HandleWenJ\\" + currentTime;
            var HandleWenJTest = AppDomain.CurrentDomain.BaseDirectory + "HandleWenJTest\\" + currentTime;
            DirectoryInfo WaitTestImgInfo = new DirectoryInfo(WaitTestImg);
            DirectoryInfo dirInfo = new DirectoryInfo(HandleWenJTest);
            IList<string> dic = new List<string>();
            //生成批次文件
            foreach (var file in WaitTestImgInfo.GetFiles())
            {
                string imgname = file.Name;
                string batchid = imgname.Split('_')[1];
                TestCopyImgDaoFile(file.FullName, batchid);//测试生成批次文件
            }
            if (!Directory.Exists(HandleWenJTest))
            {
                MessageBox.Show(HandleWenJTest + "不存在");
                return null;
            }
            //测试的批次文件夹（含批次的所有图片，文件夹名称就是批次名）
            foreach (var dir in dirInfo.GetDirectories())
            {
                //复制到的图片
                var batchId = HandleWenJ + "\\" + dir.Name;
                if (!Directory.Exists(batchId))
                {
                    Directory.CreateDirectory(batchId);
                }
                foreach (var file in dir.GetFiles())
                {
                    file.CopyTo(batchId + "\\" + file.Name);
                }
                Directory.Delete(dir.FullName, true);
                var name = dir.Name;
                dic.Add(name);
                break;
            }
            return dic;
        }
        private void kaishiOpenTest()
        {
            bool isHavePaper = false;
            string message = "";
            //扫描一个文件得到图片，如果有，则有纸
            IList<string> dic = GetBatchInfoDicForDir();
            isHavePaper = dic.Count > 0;// billOcr.IfHavePaper();
            Console.WriteLine("开始处理");
            // gllog.Write("启动结束");
            Process[] pro = Process.GetProcessesByName("ShiBieProject");
            Console.WriteLine("处理数" + dic.Count);
            if (dic.Count>0)
            {
                var first = dic.First();

                dic.Remove(first);
                list.Add(first);
            }
            if (pro.Length <= 5)
            {
                if (isHavePaper)
                {
                    message = "0$$扫描中";
               //      WaitData(message);
                    var firsts = list.First();
                    list.Remove(firsts);
                    string batchid = firsts;
                    startShiBie(batchid);
                    message = "0$$请横向放纸";
                //    WaitData(message);
                }
                else
                {
                    if (list.Count > 0)
                    {
                        var firstse = list.First();
                        list.Remove(firstse);
                        string batchid = firstse;
                        startShiBie(batchid);
                    }
                }

            }
            else {
                Console.WriteLine("进程数超过不做打开进程等待。。。");
            }
          
         
        }
        //选择监控文件夹
        private void btn_selectPath_Click()
        {
            string volume = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf('\\'));
            string newPaths = volume + "\\ScanPicture\\" + currentTime;
            if (!Directory.Exists(newPaths))
            {
                Directory.CreateDirectory(newPaths);
            }
            m_strImgPath.Text = newPaths;
        }
        int numpic = 0;
        public void num(int num)
        {
            numpic = num;
        }
        private string GetNewPath(string fileUrl, string batchid)
        {
            var dd = AppDomain.CurrentDomain.BaseDirectory;
            string activeDir = dd;
            string newPath = Path.Combine(activeDir, "HandleWenJ\\" + currentTime + "\\" + batchid);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            newPath += "\\" + Path.GetFileName(fileUrl);
            return newPath;
        }
        private string TestGetNewPath(string fileUrl, string batchid)
        {
            var dd = AppDomain.CurrentDomain.BaseDirectory;
            string activeDir = dd;
            string newPath = Path.Combine(activeDir, "HandleWenJTest\\" + currentTime + "\\" + batchid);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            newPath += "\\" + Path.GetFileName(fileUrl);
            return newPath;
        }
    }
}